package com.zdp.algorithm.linkedlist;

import java.util.Scanner;

/**
 * 打印两个有序链表的公共部分 (升序）
 * 打印相同的值
 * @author ZhengDp
 * @Date 2023/1/28 23:02
 */
public class PrintCommonPart {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        PrintCommonPartImpl impl = new PrintCommonPartImpl();
        while(in.hasNext()){
            int n = in.nextInt();
            Node head1 = new Node();
            Node p = head1;
            for(int i = 0; i < n ; i++ ) {
                int tmp = in.nextInt();
                Node t = new Node(tmp);
                t.next = p.next;
                p.next = t;
                p = t;
            }
            int m = in.nextInt();
            Node head2 = new Node();
            p = head2;
            for(int i = 0; i < m; i ++ ){
                int tmp = in.nextInt();
                Node t = new Node(tmp);
                t.next = p.next;
                p.next = t;
                p = t;
            }
            impl.printCommonPart(head1,head2);
        }
    }
}

/**
 * 带有哨兵的链表
 */
class PrintCommonPartImpl {

    public void printCommonPart(Node head1,Node head2){
        head1 = head1.next;
        head2 = head2.next;
        while(head1 != null && head2 != null) {
            int h1 = head1.value;
            int h2 = head2.value;
            if(h1 == h2) {
                System.out.print(h1 + " ");
                head2 = head2.next;
                head1 = head1.next;
            }else if( h1 < h2) {
                head1 = head1.next;
            }else {
                head2 = head2.next;
            }
        }
    }
}


